//
//  MapViewController.m
//  ClassifyShop
//
//  Created by yuyao on 15/3/22.
//  Copyright (c) 2015年 yuyao. All rights reserved.
//

#import "MapViewController.h"
#import "GUIDefine.h"
#import "KCAnnotation.h"
@interface MapViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>

@property (nonatomic,strong)MKMapView *map;
@property (nonatomic,strong)CLLocationManager *locationManager;
@end

@implementation MapViewController
@synthesize map,currentRestCore;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {

    }
    return self;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"地图";
    ADDLEFTBTN(self, @"back.png", @"", @selector(back));
    //定位管理器
    _locationManager=[[CLLocationManager alloc]init];
    //设置代理
    _locationManager.delegate=self;
    //设置定位精度
    _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    //定位频率,每隔多少米定位一次
    CLLocationDistance distance=10.0;//十米定位一次
    _locationManager.distanceFilter=distance;
   [_locationManager startUpdatingLocation];
    
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务当前可能尚未打开，请设置打开！");
        return;
    }
    [_locationManager requestWhenInUseAuthorization];


    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.map = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, kAppScreenWidth, kAppScreenHeight-64)];
    self.map.mapType = MKMapTypeStandard ;
    [self.map setDelegate:self];
    [self.view addSubview:self.map];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];

    if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied){
    
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"请进入设置 打开定位功能" message:nil delegate:nil
                                              cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
        
    }
}
- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
}
-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation fromLocation: (CLLocation *)oldLocation
{
   // NSTimeInterval howRecent = [newLocation.timestamp timeIntervalSinceNow];
   // if(howRecent < -10) return; //离上次更新的时间少于10秒
    //    if(newLocation.horizontalAccuracy > 100) return; //精度> 100米
    //经度和纬度
    double lat = newLocation.coordinate.latitude;
    double lon = newLocation.coordinate.longitude;
    
    NSLog(@"%f %f",lon,lat);
    
    //调整地图位置和缩放比例,第一个参数是目标区域的中心点，第二个参数：目标区域南北的跨度，第三个参数：目标区域的东西跨度，单位都是米
    MKCoordinateRegion viewRegion = MKCoordinateRegionMakeWithDistance(newLocation.coordinate, 10000, 10000);
    
    //重新设置地图视图的显示区域
    [self.map setRegion:viewRegion animated:YES];
    // 实例化 MapLocation 对象
    
    KCAnnotation *annotation1=[[KCAnnotation alloc]init];
    annotation1.title=self.currentRestCore.name ;
    annotation1.subtitle=[[self.currentRestCore.addrArray  objectAtIndex:0] objectForKey:@"address"];
    annotation1.coordinate=newLocation.coordinate;
    [self.map addAnnotation:annotation1];
    
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    switch ([CLLocationManager authorizationStatus]) {
        case kCLAuthorizationStatusNotDetermined:
            NSLog(@"kCLAuthorizationStatusNotDetermined");
            
            break;
        case kCLAuthorizationStatusDenied:
            NSLog(@"kCLAuthorizationStatusDenied");
            
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            NSLog(@"kCLAuthorizationStatusAuthorizedAlways");
            
            break;
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            NSLog(@"kCLAuthorizationStatusNotDetermined");

            //启动跟踪定位
            [_locationManager startUpdatingLocation];
            break;
        default:
            break;
    }
}
#pragma mark mapView Delegate 地图 添加标注时 回调
- (MKAnnotationView *) mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>) annotation {
    // 获得地图标注对象
    MKPinAnnotationView * annotationView = (MKPinAnnotationView *)[self.map dequeueReusableAnnotationViewWithIdentifier:@"PIN_ANNOTATION"];
    if (annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"PIN_ANNOTATION"];
    }
    // 设置大头针标注视图为紫色
    annotationView.pinColor = MKPinAnnotationColorPurple ;
    // 标注地图时 是否以动画的效果形式显示在地图上
    annotationView.animatesDrop = YES ;
    // 用于标注点上的一些附加信息
    annotationView.canShowCallout = YES ;
    
    return annotationView;
    
}

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
    self.map.centerCoordinate = userLocation.location.coordinate;
}

- (void)mapViewDidFailLoadingMap:(MKMapView *)theMapView withError:(NSError *)error {
    NSLog(@"error : %@",[error description]);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
